package com.huika.renrench.control.my.certification.activity;


import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.text.InputFilter;
import android.text.Spanned;
import android.widget.EditText;

/**
 * 
 * @description：字数限制和空格输入限制
 * @author zc
 * @date 2015年2月2日 上午10:16:03
 */
public class WordsLengthFilter implements InputFilter {

	private EditText editText;
	private int count;
	private boolean canInputSpace;
	private boolean isMyShop;
	
	public WordsLengthFilter(boolean isMyShop, EditText editText, int count) {
		this(editText, count, true);
		this.isMyShop = isMyShop;
	}
	
	public WordsLengthFilter(EditText editText, int count) {
		this(editText, count, true);
	}
	
	public WordsLengthFilter(EditText editText, int count, boolean canInputSpace) {
		this.editText = editText;
		this.count = count;
		this.canInputSpace = canInputSpace;
	}
	
	@Override
	public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
		String str = editText.getText().toString();
		int strCount = Utils.getInputLength(str);
		if(strCount >= this.count) {
			return "";
		} else {
			if(isLetterDigitOrChinese(source.toString()) || isChineseStr(source.toString())) {
				
			} else {
				return "";
			}
			int sourceCount = Utils.getInputLength(source.toString());
			if(strCount + sourceCount > count) {
				int canInputCount = count - strCount;
				return Utils.getStrFromInput(canInputCount, source.toString(), false);
			} else {
				if(!canInputSpace) {
					return source.toString().replace(" ", "").trim();
				}
			}
			
		}
		return source;
	}
	
	private boolean isChineseStr(String str) {
		char[] chars = str.toCharArray();
		for(int i = 0; i < chars.length; i++) {
			if(isChineseChar(String.valueOf(chars[i])) || isLetterDigit(chars[i])) {
				if(i == str.length() - 1) {
					return true;
				}
			} else {
				break;
			}
		}
		return false;
	}
	
	private boolean isLetterDigit(char c) {
		return isLetterDigitOrChinese(String.valueOf(c));
	}
	
	
	private boolean isLetterDigitOrChinese(String str) {
		String regex = "";
		if(isMyShop) {
			return true;
		} else {
			regex = "^[A-Za-z]+$";
		}
		return str.matches(regex);
	}
	
	private boolean isChineseChar(String str){
        Pattern p=Pattern.compile("[\u4e00-\u9fa5]"); 
        Matcher m=p.matcher(str); 
        return m.matches();
    }
	
}
